package com.ruoyi.back.service.impl

import cn.hutool.core.bean.BeanUtil
import cn.hutool.core.util.StrUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.baomidou.shaun.core.context.ProfileHolder
import com.ruoyi.app.common.*
import com.ruoyi.back.domain.SystemNotice
import com.ruoyi.back.domain.TemplateComment
import com.ruoyi.back.domain.TemplateRecommend
import com.ruoyi.back.domain.dto.CheckTemplateDto
import com.ruoyi.back.domain.dto.TemplateCommentSearchDto
import com.ruoyi.back.domain.vo.CheckStatusSumVo
import com.ruoyi.back.domain.vo.TemplateCommentListVo
import com.ruoyi.back.domain.vo.TemplateCommentVo
import com.ruoyi.back.enums.CheckStatusEnum
import com.ruoyi.back.mapper.TemplateCommentMapper
import com.ruoyi.back.service.AppUserService
import com.ruoyi.back.service.TemplateCategoryService
import com.ruoyi.back.service.TemplateCommentService
import com.ruoyi.back.service.TemplateService
import com.ruoyi.common.core.page.TableSupport
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class TemplateCommentServiceImpl : ServiceImpl<TemplateCommentMapper, TemplateComment>(), TemplateCommentService {


    @Autowired
    private lateinit var templateService: TemplateService

    @Autowired
    private lateinit var appUserService: AppUserService

    @Autowired
    private lateinit var templateCategoryService: TemplateCategoryService

    override fun saveTemplateComment(templateComment: TemplateComment): Data<Boolean> =
        Ok("评论成功", save(templateComment.apply {
            createBy = ProfileHolder.getProfile().id.toLong()
            categoryId = templateService.getById(templateComment.templateId)?.categoryId
            appUserService.appUserInfo(ProfileHolder.getProfile().id.toLong())?.let {
                userId = it.userId
                username = it.username
            }
        }))

    override fun templateCommentPage(templateCommentSearchDto: TemplateCommentSearchDto): PageData<TemplateCommentListVo> =
        TableSupport.buildPageRequest().let { pageDomain ->
            page(Page(pageDomain.pageNum.toLong(), pageDomain.pageSize.toLong()),
                KtQueryWrapper(TemplateComment::class.java).apply {
                    like(
                        StrUtil.isNotBlank(templateCommentSearchDto.content),
                        TemplateComment::content,
                        templateCommentSearchDto.content
                    )
                    templateCommentSearchDto.userParam?.run {
                        like(TemplateComment::userId, templateCommentSearchDto.userParam).or()
                            .like(TemplateComment::username, templateCommentSearchDto.userParam)
                    }
                    eq(
                        templateCommentSearchDto.checkStatus != null, TemplateComment::checkStatus,
                        templateCommentSearchDto.checkStatus
                    )
                    eq(
                        templateCommentSearchDto.categoryId != null,
                        TemplateRecommend::categoryId,
                        templateCommentSearchDto.categoryId
                    )
                    gt(
                        StrUtil.isNotBlank(templateCommentSearchDto.commentBeginDate),
                        SystemNotice::sendTime,
                        templateCommentSearchDto.commentBeginDate.date()
                    )
                    lt(
                        StrUtil.isNotBlank(templateCommentSearchDto.commentEndDate),
                        SystemNotice::sendTime,
                        templateCommentSearchDto.commentEndDate.date()
                    )
                    orderByDesc(TemplateComment::createTime)
                }).let { page: Page<TemplateComment> ->

                Page<TemplateCommentListVo>().apply {
                    BeanUtil.copyProperties(page, this)
                    records = page.records.takeIf { it.isNotEmpty() }?.run {
                        map {
                            TemplateCommentListVo().apply {
                                BeanUtil.copyProperties(it, this)
                                categoryName = templateCategoryService.getNameById(it.categoryId!!)
                                templateService.getById(it.templateId)?.run {
                                    templateContent = content
                                    templateTitle = title
                                    templateType = type
                                    templateCover = cover
                                }
                            }
                        }
                    }
                }.pageInfo()
            }
        }

    override fun checkTemplateComment(checkTemplateDto: CheckTemplateDto): Data<Boolean> =
        getById(checkTemplateDto.id)?.run {
            Ok("审核评论成功", updateById(apply {
                checkStatus = checkTemplateDto.checkStatus
            }))
        } ?: kotlin.run {
            Fail("不存在该资源")
        }

    override fun removeTemplateComment(ids: String): Data<Boolean> = Ok("移除评论成功", removeByIds(ids.split(",")))

    override fun getTemplateCommentPage(id: Long): PageData<TemplateCommentVo> =
        templateService.getById(id)?.let { template ->
            TableSupport.buildPageRequest().let { pageDomain ->
                page(
                    Page(pageDomain.pageNum.toLong(), pageDomain.pageSize.toLong()),
                    KtQueryWrapper(TemplateComment::class.java).eq(TemplateComment::templateId, id)
                        .eq(TemplateComment::checkStatus, CheckStatusEnum.CHECK_PASS.code)
                        .orderByDesc(TemplateComment::createTime)
                ).let { page: Page<TemplateComment> ->
                    Page<TemplateCommentVo>().apply {
                        BeanUtil.copyProperties(page, this)
                        records = page.records.takeIf { it.isNotEmpty() }?.run {
                            map {
                                TemplateCommentVo().apply {
                                    commentId = it.id
                                    appUserService.appUserInfo(it.createBy!!)?.let {
                                        username = it.username
                                        headUrl = it.headUrl
                                    }
                                    content = it.content
                                    createDate = it.createTime?.format()
                                    author = template.createBy == it.createBy
                                }
                            }
                        }
                    }.pageInfo()
                }
            }
        } ?: throw Exception("不存在该资源!")

    override fun getTemplateCheckPassComment(templateId: Long): Long =
        count(KtQueryWrapper(TemplateComment::class.java)
            .eq(TemplateComment::templateId, templateId)
            .eq(TemplateComment::checkStatus, CheckStatusEnum.CHECK_PASS.code))
            .toLong()

    override fun checkStatusSum(): Data<CheckStatusSumVo> =
        Ok("获取统计结果成功", CheckStatusSumVo().apply {
            preCheckNum = count(
                KtQueryWrapper(TemplateComment::class.java)
                    .eq(TemplateComment::checkStatus, CheckStatusEnum.PRE_CHECK.code)
            ).toLong()
            checkSuccessNum = count(
                KtQueryWrapper(TemplateComment::class.java)
                    .eq(TemplateComment::checkStatus, CheckStatusEnum.CHECK_PASS.code)
            ).toLong()
            checkFailNum = count(
                KtQueryWrapper(TemplateComment::class.java)
                    .eq(TemplateComment::checkStatus, CheckStatusEnum.CHECK_FAIL.code)
            ).toLong()
        })
}